package com.ai.trickycards.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.ai.trickycards.Constant
import com.ai.trickycards.R
import com.ai.trickycards.databinding.ActivityMainBinding
import com.ai.trickycards.entity.enumeration.GameMode
import com.ai.trickycards.ui.dialog.CheckInDialog
import com.ai.trickycards.ui.dialog.GameModeDialog
import com.ai.trickycards.utils.SP
import com.ai.trickycards.utils.Utils
import com.ai.trickycards.utils.onLifecycleState
import com.ai.trickycards.utils.startAnimationInt
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@SuppressLint("SetTextI18n")
class MainActivity : BaseActivity() {

    private val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private val requestCodeForGuide = 1
    private var currentUserScore = 0

    /**
     * chat show type：
     * 0:hide
     * 1：showTutorialMessage
     * 2:showGuideFinishMessage
     * 3:showModeMessage
     * 4:showDailyMessage
     */
    private var showChatType = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        setWindowInsets(binding.root, insetBottom = false)
        bindView()

        val openAppCount = SP.getInt(this, Constant.SP_KEY.OPEN_APP_COUNT)
        SP.putInt(this, Constant.SP_KEY.OPEN_APP_COUNT, openAppCount + 1)
        if (!SP.getBoolean(this, Constant.SP_KEY.GUIDE_SHOWED)) {
            showTutorialMessage()
        } else if (openAppCount < 2) {
            showModeMessage()
        } else if (openAppCount == 2) {
            showDailyMessage()
        }

        binding.ivHead.setOnClickListener { openActivity(ProfileActivity::class.java) }

        // 游戏Royal模式
        binding.ivGameModeRoyal.setOnClickListener {
            doClick(it) {
                GameModeDialog(this, GameMode.Royal, R.mipmap.mode_royal_card) { dialog ->
                    startGame(dialog)
                }.show()
            }
        }

        // 游戏Number模式
        binding.ivGameModeNumber.setOnClickListener {
            doClick(it) {
                GameModeDialog(this, GameMode.Number, R.mipmap.mode_number_card) { dialog ->
                    startGame(dialog)
                }.show()
            }

        }

        // 游戏Complex模式
        binding.ivGameModeComplex.setOnClickListener {
            doClick(it) {
                GameModeDialog(this, GameMode.Complex, R.mipmap.mode_complex_card) { dialog ->
                    startGame(dialog)
                }.show()
            }
        }

        // 每日签到
        binding.ivMenuDaily.setOnClickListener {
            doClick(it) {
                CheckInDialog(this, appViewModel).show()
            }
        }

        // 新手引导
        binding.ivMenuTutorial.setOnClickListener {
            doClick(it) {
                openActivity(GuideActivity::class.java)
            }
        }

        // 点击其它区域，隐藏ai对话框
        binding.root.setOnClickListener {
            doClick(it) {

            }
        }
    }

    private fun startGame(gameModeDialog: GameModeDialog) {
        val userInfo = appViewModel.userInfoFlow.value.copy()
        val gameMode = gameModeDialog.gameMode
        if (userInfo.score < gameMode.score) {
            // 用户剩余积分不够玩该模式游戏
            Toast.makeText(this, "The current points are not enough", Toast.LENGTH_SHORT).show()
            return
        }

        // 扣除对应积分后启动游戏
        gameModeDialog.dismiss()
        userInfo.score -= gameMode.score
        appViewModel.changeUserInfo(userInfo)

        openActivity(GameActivity::class.java, Bundle().apply {
            putSerializable("gameMode", gameMode)
        })
    }

    private fun bindView() {
        val userInfo = appViewModel.userInfoFlow.value
        currentUserScore = userInfo.score
        binding.tvScore.text = "$currentUserScore"

        onLifecycleState {
            appViewModel.userInfoFlow.collect { u ->
                if (currentUserScore != u.score) {
                    binding.tvScore.startAnimationInt(null, currentUserScore, u.score, duration = 400)
                    currentUserScore = u.score
                }

                binding.ivHead.setImageResource(u.headIcon)
                binding.tvNick.text = u.userName
                binding.tvLevel.text = "Level ${u.level}"
                binding.progressLevel.progress = Utils.getLevelProgress(u.level)
            }
        }
    }


    /**
     * 点击事件是否可执行，当第一次使用显示新手引导对话框时，其它区域是不能点击的
     */
    private fun doClick(v: View, block: (View) -> Unit) {
        if (showChatType in listOf(0, 3, 4)) {
            hideChat()
            block.invoke(v)
        }
    }

    /**
     * 隐藏ai对话框
     */
    private fun hideChat() {
        binding.chatView.isVisible = false
        showChatType = 0
    }

    /**
     * 首次打开app进入会弹出新手引导（home- 新手引导和home-引导结束），
     * 后面不提示 二次打开直接进入home- start game
     * 点击ok，跳转新手引导
     * 点击skip，不进入新手引导，跳转“home- start game”
     * 此对话框不能通过点击空白处关闭
     */
    private fun showTutorialMessage() {
        showChatType = 1
        binding.chatView.isVisible = true
        binding.chatView.reset()
        binding.chatView.startSpeak(
            textList = listOf(
                "Welcome I'm your Poker girl.",
                "",
                "Before the challenge begins, let me introduce the rules of the game."
            ),
            doOnEndDelay = 250
        ) {
            it.setLeftOption("Skip") {
                SP.putBoolean(this@MainActivity, Constant.SP_KEY.GUIDE_SHOWED, true)
                hideChat()
                showModeMessage()

            }.setRightOption("Ok") {
                hideChat()
                openActivityForResult(GuideActivity::class.java, requestCodeForGuide)
            }
        }
    }

    /**
     * 完成新手引导之后显示的对话框
     * 点击ok 默认进入 Tricky Royal  模式
     *
     * 此对话框不能通过点击空白处关闭
     */
    private fun showGuideFinishMessage() {
        showChatType = 2
        binding.chatView.isVisible = true
        binding.chatView.reset()
        binding.chatView.startSpeak(
            textList = listOf(
                "Congratulations on completing the beginner tutorial. Now, let's start the challenge!"
            ),
            doOnEndDelay = 250
        ) {
            it.setLeftOption("")
            it.setRightOption("Ok") {
                hideChat()
                binding.ivGameModeRoyal.callOnClick()
            }
        }
    }

    /**
     *
     * 进入此页面的情况
     * 1: 第一次打开app，新手引导对话框点击skip
     * 2: 实际玩的前3次游戏，在停留主页的界面时展示
     */
    private fun showModeMessage() {
        showChatType = 3
        binding.chatView.isVisible = true
        binding.chatView.reset()
        binding.chatView.startSpeak(
            textList = listOf(
                "Hi, there are different mode challenges for you.",
                "",
                "For better experience as newbie, I recommend you start Tricky Royal mode first."
            ),
            doOnEndDelay = 250
        ) {
            it.setLeftOption("")
            it.setRightOption("Ok") {
                hideChat()
                binding.ivGameModeRoyal.callOnClick()
            }
        }
    }

    /**
     *
     * 进入此页面的情况
     * 1: 第一次打开app，新手引导对话框点击skip
     * 2: 实际玩的前3次游戏，在停留主页的界面时展示
     */
    private fun showDailyMessage() {
        showChatType = 4
        binding.chatView.isVisible = true
        binding.chatView.reset()
        binding.chatView.startSpeak(
            textList = listOf(
                "Bingo, enjoy the poker party fully.",
                "",
                "Don't forget to claim daily points."
            ),
            doOnEndDelay = 250
        ) {
            it.setRightOption("Ok") {
                hideChat()
            }
        }
    }

    override fun onActivityResult(intent: Intent?, requestCode: Int, resultCode: Int) {
        if (requestCode == requestCodeForGuide) {
            if (resultCode == RESULT_OK) {
                lifecycleScope.launch {
                    delay(500)
                    showGuideFinishMessage()
                }

            } else if (resultCode == RESULT_CANCELED) {
                val openAppCount = SP.getInt(this, Constant.SP_KEY.OPEN_APP_COUNT)
                if (openAppCount < 2) {
                    lifecycleScope.launch {
                        delay(500)
                        showModeMessage()
                    }
                }
            }
        }
    }
}